package com.itcam.cm.product.utils;

import com.itcam.cm.model.entity.product.Category;

import java.util.ArrayList;
import java.util.List;

public class CategoryHelper {
    public static List<Category> buildTree(List<Category> categories) {
        List<Category> tree = new ArrayList<>();
        // 1. 找到所有的一级分类
        for (Category category : categories) {
            if(category.getParentId().longValue()==0){
                tree.add(findChildren(category, categories));
            }
        }
        return tree;
    }

    private static Category findChildren(Category category, List<Category> categories) {
        for (Category child : categories) {
            if(child.getParentId().longValue() == category.getId().longValue()){
                category.getChildren().add(findChildren(child,categories));
            }
        }
        if(category.getChildren()==null||category.getChildren().size()==0){
            category.setHasChildren(false);
        }
        return category;
    }
}
